<?php
/**
 * @copyright	Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access
defined('_JEXEC') or die;

/**
 * Joomla Authentication plugin
 *
 * @package		Vast.Plugin
 * @subpackage	Authentication.vast
 * @since 1.5
 */
class plgAuthenticationVast extends JPlugin
{
	/**
	 * This method should handle any authentication and report back to the subject
	 *
	 * @access	public
	 * @param	array	Array holding the user credentials
	 * @param	array	Array of extra options
	 * @param	object	Authentication response object
	 * @return	boolean
	 * @since 1.5
	 */
	function onUserAuthenticate($credentials, $options, &$response)
	{
		$db		= JFactory::getDbo();
		$query	= $db->getQuery(true);

		$query->select('id, password');
		$query->from('#__users');
		$query->where('username=' . $db->Quote($credentials['username']));
        
		$result = $db->loadObject();

		if ($result) {
            $query = $db->getQuery(true);
    
            $query->select('DISTINCT a.*');
            $query->from('#__hosocanbo AS a');
            $query->where('a.nguoidung_id = ' . (int)$user->id);
    
            $db->setQuery($query);
            $canbo = $db->loadObject();   
                                 
            $query = $db->getQuery(true);
                
            $query->insert('#__nhatkyhethong');
            $query->set('thoigian = ' . $db->quote(date('Y-m-d')));
            $query->set('ip = ' . $db->quote($_SERVER['REMOTE_ADDR']));
            $query->set('mota = ' . $db->quote('Đăng nhập hệ thống ứng dụng viện khoa học và công nghệ Việt Nam'));
            $query->set('nguoidung_id = ' . (int)$result->id);
            if ($canbo !== NULL)
                $query->set('hosocanbo_id = ' . (int)$canbo->id);
    
            $db->setQuery($query);
                        
            if (!$db->query()) {
                JError::raiseError(500, $db->getErrorMsg());
            }        
        }        
	}
}
